<?php

if (!isset($_COOKIE["checkLoginAdm"])) {
	
	header("Location: index.php");
}
?>
<?php

require("php/config.php");
require("php/postgres.php");

function validate_normal($value) {

	return preg_match("/[a-zA-Z ]+/", $value);
}

function validate_duracao($value) {

	return preg_match("/[0-9]+/", $value);
}

function validate_sin($value) {

	return preg_match("/[A-Za-z0-9 .!,:;'\"-+=()*&¨%$#@<>^~{}][A-Za-z0-9 .!,:;'\"-+=()*&¨%$#@<>^~{}]*/", $value);
}


try {
	
	$confs = $GLOBALS["CONFIGS"]["PSQL_DB"];
	$pgcon = new PostgresConnection($confs["HOST"], $confs["PORT"], $confs["USER"], $confs["PASSWORD"], $confs["DATABASE"]);
	$atores = array();
	
	for ($i = 1; !empty($_POST["ator$i"]); $i++) {
	
		$atores[] = $_POST["ator$i"];
	}
	
	$mand_fields = array(
						 	array("field" => "name", "val_func" => "validate_normal"),
							array("field" => "nacionalidade", "val_func" => "validate_normal"),
							array("field" => "empresa", "val_func" => "validate_normal"),
							array("field" => "duracao", "val_func" => "validate_duracao"),
							array("field" => "categoria", "val_func" => "validate_normal"),
							array("field" => "sinopse", "val_func" => "validate_sin"),
							array("field" => "censura", "val_func" => "validate_duracao")
						 );
	
	foreach ($mand_fields as $field) {
	
		if (empty($_POST[$field["field"]]) || !call_user_func($field["val_func"], $_POST[$field["field"]])) {
			
			echo $_POST[$field["field"]];
			echo $field["field"];
			header("Location: addFilme.php?error=1");
		}
	}
	
	if (!empty($_FILES["foto"])) {
		
		print_r($_FILES);
		$ext_p = strrpos($_FILES["foto"]["name"], ".");
		$ext = substr($_FILES["foto"]["name"], $ext_p);
		$file = "miniaturasfilmes/" . str_replace(" ", "_", $_POST["name"]) . $ext;
		move_uploaded_file($_FILES["foto"]["tmp_name"], $file);
		
	}
	
	if (!$pgcon->addFilme($_POST["name"], $_POST["nacionalidade"], $_POST["empresa"], $_POST["duracao"],
							$_POST["categoria"], $atores, $_POST["censura"], $_POST["sinopse"], $file)) {
	
		header("Location: addFilme.php?error=1");
		exit();
	}
	
	header("Location: addFilme.php?error=0");
	exit();
} catch (PostgresConnectionException $pce) {
} catch (InvalidFieldValueException $ifve){
	
}

//header("Location: addFilme.php?error=1");
?>